#!/usr/bin/perl
#
# ctwitim - a read-only command line client for Twitter

use strict;
use warnings;
use FindBin;
use lib "$FindBin::Bin";
use Getopt::Long qw(:config auto_help);
use Pod::Usage;
use AnyEvent;

use Twitim::XMPP;
use Twitim::Twitter;
use Twitim::NetBase;
use Twitim::Config;

binmode STDOUT, ':utf8';

my @all_message_id;

my $cfg;
my $cfg_file = "$ENV{'HOME'}/.twitimrc";
if ( -e $cfg_file ) {
    $cfg = Twitim::Config->new($cfg_file);
    $cfg->read;
}

GetOptions(
    'xmpp=s'    => \$cfg->{'default'}->{'xmpp_user'},
    'key=s'     => \$cfg->{'default'}->{'xmpp_pass'},
    'twitter=s' => \$cfg->{'default'}->{'twitter_user'},
    'pass=s'    => \$cfg->{'default'}->{'twitter_pass'},
);

my $j = AnyEvent->condvar;

my $xmpp = Twitim::XMPP->new(
    userid   => $cfg->{'default'}->{'xmpp_user'},
    password => $cfg->{'default'}->{'xmpp_pass'},
    cb       => { message => \&check_message }
);

my $twitter = Twitim::Twitter->new(
    userid   => $cfg->{'default'}->{'twitter_user'},
    password => $cfg->{'default'}->{'twitter_pass'},
    access_token  => $cfg->{'default'}->{'access_token'},
    access_secret => $cfg->{'default'}->{'access_secret'},
    cb       => { message => \&check_message }
);
$twitter->friends_timeline('Timeline');
$twitter->set_access_timer( 'friends_timeline', 60 );

$j->wait;

sub check_message {
    my $arg_ref = shift;

    my $user_id = $arg_ref->{'user_id'};
    my $id      = $arg_ref->{'message_id'};

    if ( defined $id ) {
        return if ( grep /$id/, @all_message_id );
        push( @all_message_id, $id );
    }

    printf "(%s) %s %s\n",
        Twitim::NetBase->get_formatted_time( $arg_ref->{'unixtime'} ),
        set_color(
        "$user_id:", Twitim::NetBase->get_color( $user_id, undef, 1 )
        ),
        $arg_ref->{'body'};
}

sub set_color {
    my ( $text, $color ) = @_;
    $text = "\e[1;38;5;" . $color . "m$text\e[0m";    # for xterm-256color
    return $text;
}

__END__

=head1 NAME

ctwitim - a read-only command line client for Twitter

=head1 SYNOPSIS

ctwitim [--twitter=twitter_id] [--password=twitter_password] 
        [--xmpp=xmpp_id] [--key=xmpp_password]

=head1 OPTIONS

=over 8

=item B<-t, --twitter>

Set a Twitter ID.

=item B<-p, --password>

Set a Twitter password.

=item B<-x, --xmpp>

Set an XMPP ID.

=item B<-k, --key>

Set an XMPP password.

=item B<-h, --help>

Print a brief help message and exits.

=back

=head1 DESCRIPTION

ctwitim is a read-only command line client for Twitter.  It reads
Twitter statuses with XMPP and web API.  

=head1 NOTES

ctwitim reads default account configurations from ~/.twitimrc.

=cut
